package com.yunshang.ys.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
//import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

//import com.nostra13.universalimageloader.core.DisplayImageOptions;
//import com.nostra13.universalimageloader.core.assist.ImageScaleType;
//import com.risenbsy.ixing.R;

import java.lang.reflect.Method;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/11/16 0016.
 */

public class ComplexUtil {

    private static Context mApplicationContent;
    private static Resources resources;
    private static String[] MANUFACTURERS = new String[]{"Meizu"};
    private static String[] MODELS = new String[]{"M040"};

    public static void initialize(Context applicationContext) {
        mApplicationContent = applicationContext;
        resources = mApplicationContent.getResources();
    }

    //通过资源图片获得一个bitmap 对象
    public static Bitmap getBitmap(Context context, int imageId) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), imageId);
        return bitmap;
    }

    //通过资源图片获得一个Drawable对象
    public static Drawable getDrawable(int imageId) {
        Drawable img;
        if (Build.VERSION.SDK_INT > 21) {
            img = mApplicationContent.getResources().getDrawable(imageId, null);
        } else {
            img = ContextCompat.getDrawable(mApplicationContent, imageId);
        }
//      img.setBounds(0,0,img.getMinimumWidth(),img.getMinimumHeight());
        return img;
    }


    /**
     * 保存数据到share中
     *
     * @param fileName:文件名
     * @param key:key名
     * @param data:key对应value
     */
    public static void saveData(String fileName, String key, Object data) {

        String type = data.getClass().getSimpleName();
        SharedPreferences sharedPreferences = mApplicationContent
                .getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        if ("Integer".equals(type)) {
            editor.putInt(key, (Integer) data);
        } else if ("Boolean".equals(type)) {
            editor.putBoolean(key, (Boolean) data);
        } else if ("String".equals(type)) {
            editor.putString(key, (String) data);
        } else if ("Float".equals(type)) {
            editor.putFloat(key, (Float) data);
        } else if ("Long".equals(type)) {
            editor.putLong(key, (Long) data);
        }
        editor.commit();
    }

    /**
     * 从文件中取数据
     *
     * @param fileName:文件名
     * @param key:key名
     * @param defValue:默认值
     * @return
     */
    public static Object getData(String fileName, String key, Object defValue) {
        String type = null;
        if (defValue != null)
            type = defValue.getClass().getSimpleName();
        SharedPreferences sharedPreferences = mApplicationContent.getSharedPreferences
                (fileName, Context.MODE_PRIVATE);

        //defValue为为默认值，如果当前获取不到数据就返回它
        if ("Integer".equals(type)) {
            return sharedPreferences.getInt(key, (Integer) defValue);
        } else if ("Boolean".equals(type)) {
            return sharedPreferences.getBoolean(key, (Boolean) defValue);
        } else if ("String".equals(type)) {
            String string = sharedPreferences.getString(key, (String) defValue);
            if (!TextUtils.isEmpty(string))
                return sharedPreferences.getString(key, (String) defValue);
            else return (String) defValue;
        } else if ("Float".equals(type)) {
            return sharedPreferences.getFloat(key, (Float) defValue);
        } else if ("Long".equals(type)) {
            return sharedPreferences.getLong(key, (Long) defValue);
        }
        return null;
    }

    /**
     * 删除数据
     */
    public static void deleteData(String fileName) {
        SharedPreferences sharedPreferences = mApplicationContent.getSharedPreferences
                (fileName, Context.MODE_PRIVATE);
        sharedPreferences.edit().clear().commit();
    }

    public static void setTitleHeight(View title, View titleBar, View statBar) {
        int statusBarHeight = 0;
        //获取status_bar_height资源的ID
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight = resources.getDimensionPixelSize(resourceId);
        }
        ViewGroup.LayoutParams params = statBar.getLayoutParams();
        params.height = statusBarHeight;
        statBar.setLayoutParams(params);
        ViewGroup.LayoutParams params1 = titleBar.getLayoutParams();
        ViewGroup.LayoutParams params2 = title.getLayoutParams();
        params2.height = statusBarHeight + params1.height;
        title.setLayoutParams(params2);


    }

    //设置statusBar 高度
    public static void setStatusBarHeight(View view) {
        int statusBarHeight = 0;
        //获取status_bar_height资源的ID
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        if (Build.VERSION.SDK_INT >= 19) {
            if (resourceId > 0) {
                //根据资源ID获取响应的尺寸值
                statusBarHeight = resources.getDimensionPixelSize(resourceId);
            }
            ViewGroup.LayoutParams params = view.getLayoutParams();
            params.height = statusBarHeight;
            view.setLayoutParams(params);
        }
    }

    //获得NavigationBar高度
    public static void setNavigationBarHeight(View view) {
        //获取是否存在NavigationBar
        boolean hasNavigationBar = false;
        int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = resources.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {

        }
        int navigationBarHeight = 0;
        //返回NavigationBar高度
        if (hasNavigationBar && !isSpecial()) {
            int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
            navigationBarHeight = resources.getDimensionPixelSize(resourceId);
        }
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.height = navigationBarHeight;
        view.setLayoutParams(params);
    }

    //判断手机型号是否在特殊型号列表内
    private static boolean isSpecial() {
        String thisModel = Build.MODEL;
        for (String model : MODELS) {
            if (model.equals(thisModel)) {
                return true;
            }
        }
        return false;
    }


    public static boolean isMail(String email) {
        if (Pattern.matches("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$",
                email))
            return true;
        else return false;
    }


    public static boolean isMobile(String phone) {
        if (Pattern.matches("^((17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$", phone))
            return true;
        else return false;
    }

    public static boolean isFormPWD(String pwd) {
        if (Pattern.matches("(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}", pwd))
            return true;
        else return false;
    }

    // 时间戳
    public static String TimeStamp2Date(String timestampString) {
//        Long timestamp = Long.parseLong(timestampString) * 1000;
//        String date = new java.text.SimpleDateFormat(formats).format(new java.util.Date(timestamp));
//        return date;
        Long timestamp = Long.parseLong(timestampString) * 1000;
//        String date = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new java.util.Date(timestamp));
        String date = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm").format(new java.util.Date(timestamp));
        return date;
    }

    // 时间戳
    public static String TimeStamp1Date(String timestampString) {
//        Long timestamp = Long.parseLong(timestampString) * 1000;
//        String date = new java.text.SimpleDateFormat(formats).format(new java.util.Date(timestamp));
//        return date;
        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm").format(new java.util.Date(timestamp));
        return date;
    }

//    public static DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
//            .showImageOnLoading(R.mipmap.noimage2x)
//            .showImageOnFail(R.mipmap.noimage2x)
//            .showImageForEmptyUri(R.mipmap.noimage2x)
//            .cacheInMemory(true)
//            .cacheOnDisk(false)
//            .bitmapConfig(Bitmap.Config.RGB_565)
//            .resetViewBeforeLoading(false)
//            .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
//            .build();


    /**
     * 半角转换为全角
     *
     * @param input
     * @return
     */
    public static String ToDBC2(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    // 半角转化为全角的方法
    public static String ToSBC(String input) {
        // 半角转全角：
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 32) {
                c[i] = (char) 12288;
                continue;
            }
            if (c[i] < 127 && c[i] > 32)
                c[i] = (char) (c[i] + 65248);
        }
        return new String(c);
    }

    // 全角转化为半角的方法
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (isChinese(c[i])) {
                if (c[i] == 12288) {
                    c[i] = (char) 32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char) (c[i] - 65248);
            }
        }
        return new String(c);
    }

    //    ps：利用编码的方式判断字符是否为汉字的方法：
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }


//    public static boolean isSlideToBottom(RecyclerView recyclerView) {
//        if (recyclerView == null) return false;
//        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange())
//            return true;
//        return false;
//    }


    /**
     * 拼接字符串
     *
     * @param list
     * @return
     */
    public static String appendString(List<String> list) {
        StringBuffer s = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                s.append(list.get(i));
            } else {
                s.append("," + list.get(i));
            }
        }
        return s.toString();
    }


    /**
     * View to Bitmap
     *
     * @param addViewContent
     * @return
     */
    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);

        addViewContent.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0, addViewContent.getMeasuredWidth(), addViewContent.getMeasuredHeight());

        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }

    /**
     * 圆角bitmap
     *
     * @param bitmap
     * @param roundPx
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        Bitmap output;
        if (bitmap.getWidth() > bitmap.getHeight())
            output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                    .getWidth(), Bitmap.Config.ARGB_8888);
        else output = Bitmap.createBitmap(bitmap.getHeight(), bitmap
                .getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);


        final int color = 0xff009dff;
        final Paint paint = new Paint();
        final Rect rect;
        final RectF rectF;
        if (bitmap.getWidth() > bitmap.getHeight()) {
            rectF = new RectF(0, 0, bitmap.getWidth(), bitmap.getWidth());
            rect = new Rect(10, 10, bitmap.getWidth() - 10, bitmap.getWidth() - 10);
        } else {
            rectF = new RectF(0, 0, bitmap.getHeight(), bitmap.getHeight());
            rect = new Rect(10, 10, bitmap.getHeight() - 10, bitmap.getHeight() - 10);
        }

        paint.setAntiAlias(true);
//        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * 椭圆bitmap
     *
     * @param bitmap
     * @return
     */
    public static Bitmap getOvalBitmap(Bitmap bitmap) {

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                .getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);

        canvas.drawOval(rectF, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    /**
     * 方形切图
     *
     * @param bitmap
     * @param isRecycled
     * @return
     */
    public static Bitmap ImageCrop(Bitmap bitmap, boolean isRecycled) {

        if (bitmap == null) {
            return null;
        }

        int w = bitmap.getWidth(); // 得到图片的宽，高
        int h = bitmap.getHeight();

        int wh = w > h ? h : w;// 裁切后所取的正方形区域边长

        int retX = w > h ? (w - h) / 2 : 0;// 基于原图，取正方形左上角x坐标
        int retY = w > h ? 0 : (h - w) / 2;

        Bitmap bmp = Bitmap.createBitmap(bitmap, retX, retY, wh, wh, null,
                false);
        if (isRecycled && bitmap != null && !bitmap.equals(bmp)
                && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }

        // 下面这句是关键
        return bmp;// Bitmap.createBitmap(bitmap, retX, retY, wh, wh, null,
        // false);
    }

    //设置输入法,如果当前页面输入法打开则关闭
    public static void hideInputMethod(Activity activity) {
        View a = activity.getCurrentFocus();
        if (a != null) {
            InputMethodManager imm = (InputMethodManager) activity.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            try {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 强制显示输入法
     */
    public static void toggleSoftInput(Activity activity) {
        View view = activity.getCurrentFocus();
        try {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void closeKeyboard(Activity acitivty) {
        View view = acitivty.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) acitivty.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * unicode 转字符串
     */
    public static String unicode2String(String unicode) {

        StringBuffer string = new StringBuffer();

        String[] hex = unicode.split("\\\\u");

        for (int i = 1; i < hex.length; i++) {

            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);

            // 追加成string
            string.append((char) data);
        }

        return string.toString();
    }

    /**
     * 字符串转换unicode
     */
    public static String string2Unicode(String string) {

        StringBuffer unicode = new StringBuffer();

        for (int i = 0; i < string.length(); i++) {

            // 取出每一个字符
            char c = string.charAt(i);
            if (c < 256)//ASC11表中的字符码值不够4位,补00
            {
                unicode.append("\\u00");
            } else {
                unicode.append("\\u");
            }
            // 转换为unicode
            unicode.append(Integer.toHexString(c));
        }

        return unicode.toString();
    }

    /**
     * 给edittext设置过滤器 过滤emoji
     *
     * @param et
     */
    public static void setEmojiFilter(EditText et) {
        InputFilter emojiFilter = new InputFilter() {
            Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher matcher = pattern.matcher(source);
                if (matcher.find()) {
                    return "";
                }
                return null;
            }
        };
        et.setFilters(new InputFilter[]{emojiFilter});
    }

    /**
     * 字符串转换unicode
     */
    public static String string2Unicode2(String string) {

        StringBuffer unicode = new StringBuffer();

        for (int i = 0; i < string.length(); i++) {

            // 取出每一个字符
            char c = string.charAt(i);

            // 转换为unicode
            unicode.append("\\u" + Integer.toHexString(c));
        }

        return unicode.toString();
    }

    /**
     * unicode 转字符串
     */
    public static String unicode2String2(String unicode) {

        StringBuffer string = new StringBuffer();

        String[] hex = unicode.split("\\\\u");

        for (int i = 1; i < hex.length; i++) {

            if (hex[i].equals("20")) {
                string.append(" ");
            } else {
                // 转换出每一个代码点
                int data = Integer.parseInt(hex[i], 16);
                // 追加成string
                string.append((char) data);
            }

        }
        return string.toString();
    }


    public static Context getmApplicationContent() {
        return mApplicationContent;
    }


    public static  boolean inRangeOfView (View view, MotionEvent ev) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];
        if (ev.getX() < x || ev.getX() > (x + view.getWidth()) || ev.getY() < y || ev.getY() > (y + view.getHeight())) {
            return false;
        }
        return true;
    }
}

